package com.cuit.riskassessment.service.impl;


import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cuit.riskassessment.dao.area.AreaMapper;
import com.cuit.riskassessment.dao.project.ProjectMapper;
import com.cuit.riskassessment.service.AreaService;
import com.cuit.riskassessment.util.Tree;
import com.cuit.riskassessment.vo.Area;
@Service(value="areaService")
public class AreasServiceImpl implements AreaService {
	@Autowired
	@Resource(name="areaMapper")
	private AreaMapper areaMapper;
	
	@Autowired
	@Resource(name="projectMapper")
	private ProjectMapper projectMapper;
	@Override
	public boolean addArea(Area area) {
		// TODO Auto-generated method stub
		
		Integer  count = this.areaMapper.getCount();
		if(count==null)count = 0;
		if(count%2==0)
		{
			count+=1;
		}else
		{
			count+=2;
		}
		area.setId(count);
		return this.areaMapper.addArea(area) >0?true:false;
	}

	@Override
	public boolean updateArea(Area area) {
		return 	this.areaMapper.updateArea(area)>0?true:false;
	}

	@Override
	public boolean delArea(int id) {
		 return this.areaMapper.delArea(id)>0?true:false;
	}

	@Override
	public Object getAreas(Integer pid) {
		//父亲节点
		Tree tree = this.areaMapper.getTree(pid==null?-1:pid);
		//区域树
		List<Tree> trees = this.areaMapper.getAreas(pid);
		
		for(Tree t2 : trees)
		{
			if(tree!=null)
			{
				t2.setParentname(tree.getText());
			}else
			{
				t2.setParentname("区域信息");
			}
		}
		//TODO 项目树
		List<Tree> leaf = this.projectMapper.getTrees(pid);
		
		for(Tree t : leaf)
		{
			t.setLeaf(true);
			if(tree!=null)
			{
				t.setTd(tree.getTd());
				t.setParentname(tree.getText());
				System.out.println(t.getTd()+"================="+tree.getText());
			}else
			{
				t.setParentname("区域信息");
			}
			trees.add(t);
			
		}
		return trees;
	}

	/**
	 * 选择区域
	 */
	@Override
	public Object getAreaById(Integer id) {
		// TODO Auto-generated method stub
		return this.areaMapper.getTree(id==null?-1:id);
	}

	@Override
	public Integer getAreaCount(Integer id) {
		// TODO Auto-generated method stub
		return this.areaMapper.getAreaCount(id);
	}

	@Override
	public List<Tree> getDetail(Integer pid) {
		// TODO Auto-generated method stub
			//父级区域信息
		   Tree tree = this.areaMapper.getTree(pid==null?-1:pid);
			//区域树
			List<Tree> trees = this.areaMapper.getAreas(pid);
			
			for(Tree t2 : trees)
			{
				t2.setNumber(this.areaMapper.getAreaCount(t2.getId()));
				if(tree!=null)t2.setUpname(tree.getText());
			}
			
			//TODO 项目树
			List<Tree> leaf = this.projectMapper.getTrees(pid);
			
			for(Tree t : leaf)
			{
				t.setLeaf(true);
				if(tree!=null){
					t.setTd(tree.getTd());
					t.setUpname(tree.getText());
				}
				trees.add(t);
			}
			return trees;
	}
	
	
	

}
